package com.youhome.wechat.config;

import com.youhome.service.service.TokenService;
import com.youhome.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
@Slf4j
public class AuthTokenProvider implements AuthenticationProvider {

    @Autowired
    TokenService tokenService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null && auth.isAuthenticated()) {
            return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), null, new ArrayList<>());
        }
        String token = (String) authentication.getPrincipal();
        if (token != null) {
            if(TokenUtils.isExpired(token)) {
                if (!tokenService.checkTokenByWX(token)) {
                    throw new CredentialsExpiredException("无效 Access Token");
                }
            }else{
                throw new CredentialsExpiredException("Access Token 已经过期");
            }
        } else {
            throw new BadCredentialsException("无效的Token");
        }
        log.debug("Authenticated successfully.");
        return new UsernamePasswordAuthenticationToken(token, null, new ArrayList<>());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
